﻿using System;
using System.Linq.Expressions;
using Tszy.Unlimited.Base.Collections;

namespace Tszy.Unlimited.Base.Objects
{
    /// <summary>
    ///
    /// </summary>
    public class ObjectManager
    {
        private static readonly InstanceCreate _instanceCreate = new();

        #region 创建对象

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <returns></returns>
        public static TSource CreateInstance<TSource>()
        {
            return (TSource)CreateInstance(typeof(TSource));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object CreateInstance(Type type)
        {
            return _instanceCreate.InstanceCache(type);
        }

        /// <summary>
        ///
        /// </summary>
        private class InstanceCreate
        {
            private readonly MonoConcurrentDictionary<Type, Func<object>> _objectTypes = new();

            public object InstanceCache(Type key)
            {
                if (!_objectTypes.ContainsKey(key))
                {
                    _objectTypes[key] = CreateInstance(key);
                }

                return _objectTypes[key]();
            }

            private static Func<object> CreateInstance(Type type)
            {
                NewExpression newExp = Expression.New(type);
                Expression<Func<object>> lambdaExp = Expression.Lambda<Func<object>>(newExp, null);
                Func<object> func = lambdaExp.Compile();
                return func;
            }
        }

        #endregion 创建对象
    }
}